package com.xy.frame.controller;

import java.awt.image.BufferedImage;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.google.common.collect.Maps;
import com.xy.commons.ImgUtil;
import com.xy.commons.PageUtil;
import com.xy.frame.model.AjaxJson;
import com.xy.frame.service.UserService;

/**
 * @author Administrator
 * 用户管理控制器
 */
@Controller
@RequestMapping("/user")
public class UserController {

	Logger logger = LoggerFactory.getLogger(UserController.class);
    @Autowired
    UserService userService;
      
    /**
     * @param currentPage
     * @param pageSize
     * @return
     * 查询菜单列表数据
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @ResponseBody
    public AjaxJson list(HttpServletRequest request,@RequestParam(value = "currentPage",defaultValue = "1") int currentPage,@RequestParam(value = "pageSize",defaultValue = "10") int pageSize){
        AjaxJson j = new AjaxJson();
        Map<String,Object> params = Maps.newHashMap();
        String loginNum= request.getParameter("loginNum");
        params.put("start",(currentPage -1)*pageSize);// > start
        params.put("end",currentPage*pageSize);  // <=  end
        if(!StringUtils.isEmpty(loginNum)){
            params.put("loginNum",loginNum);  
        }
        Map<String,Object> pageList =  userService.queryUserListByPage(params);
        pageList.put(PageUtil.CURRENT,currentPage);
        pageList.put(PageUtil.PAGESIZE,pageSize);
        Integer t  = Integer.valueOf(pageList.get(PageUtil.TOTALS).toString());
        pageList.put(PageUtil.TOTALPAGE,PageUtil.getTotalPage(t,pageSize));
        j.setObj(pageList);
        if (logger.isDebugEnabled()) {
            logger.debug("请求【/user/list】处理,响应对象【"+j+"】");
        }
        return j;
    }

    /**
     * @param type
     * @param model
     * @return
     * 查看、增加、修改菜单页面
     */
    @RequestMapping(value = "/toUserPage", method = RequestMethod.GET)
    public String toMenuPage(@RequestParam("type") String type,Model model,HttpServletRequest request){
        if (logger.isDebugEnabled()) {
            logger.debug("请求【/metro/user/userPage】处理页面【/view/metro/user/userPage.jsp】");
        }
        model.addAttribute("type",type);//查看-0，增加 -1，修改-2
        if("2".equals(type)){
        	String loginNum = request.getParameter("loginNum");
        	model.addAttribute("loginNum",loginNum);
        }
        return "metro/user/userPage";
    }
    /**
     * @param menuNum
     * @return
     * 获取一个用户详细信息
     */
    @RequestMapping(value = "/getUser", method = RequestMethod.GET)
    @ResponseBody
    public AjaxJson getUser(@RequestParam("loginNum") String loginNum){
        AjaxJson j = new AjaxJson();
       
        Map<String,Object> userMap = userService.getUserByLoginName(loginNum);
        j.setObj(userMap);
        if (logger.isDebugEnabled()) {
            logger.debug("请求【/metro/user/getUser】处理,响应对象【"+j+"】");
        }
        return j;
    }
    /**
     * @param loginName
     * @return
     * 上传用户头像
     */
    @RequestMapping(value = "/uploadImg", method = RequestMethod.POST)
    @ResponseBody
    public AjaxJson uploadImg(HttpServletRequest request, @RequestParam("fileInput") MultipartFile file,@RequestParam("loginName") String loginName){
        AjaxJson j = new AjaxJson();
        if (!file.isEmpty()) {
            try {
            	 String type[] = file.getOriginalFilename().split("[.]");
                byte[] bytes = file.getBytes();
                String filepath = request.getSession().getServletContext().getRealPath("/WEB-INF/resources/img/about-us");
                File imgFile = new File(filepath,loginName+"."+type[type.length-1]);
                if(imgFile.exists()){
                	imgFile.delete();
                	imgFile.createNewFile();
                }
                
                File smallFile = new File(filepath,loginName+"-small."+type[type.length-1]);
                File lockFile = new File(filepath,loginName+"-lock."+type[type.length-1]);
                if(smallFile.exists()){
                	smallFile.delete();
                	smallFile.createNewFile();
                }
                if(lockFile.exists()){
                	lockFile.delete();
                	lockFile.createNewFile();
                }
                BufferedOutputStream stream =
                        new BufferedOutputStream(new FileOutputStream(imgFile));
                stream.write(bytes);
                stream.close();
                //创建小头像  29*29  
                ImgUtil m = new ImgUtil();
            	InputStream is = new FileInputStream(imgFile);
            	BufferedImage image = m.readImage(is);
            	//double[] size29 = m.zoomSize(image, 29, 29);
        		m.writeImage(m.zoom(image, 29, 29), type[type.length-1], smallFile);
                //创建大头像  167*167
        		//double[] size167 = m.zoomSize(image, 167, 167);
        		m.writeImage(m.zoom(image, 167,167 ),  type[type.length-1], lockFile);
                 j.setObj(loginName);
            } catch (Exception e) {
                j.setSuccess(false);
                j.setMsg("You failed to upload " + file.getOriginalFilename() + " => " + e.getMessage());
            }
        } else {
            j.setSuccess(false);
            j.setMsg("You failed to upload " + file.getOriginalFilename() + " because the file was empty.");
        }
        if (logger.isDebugEnabled()) {
            logger.debug("请求【/metro/user/getUser】处理,响应对象【"+j+"】");
        }
        return j;
    }
    /**
     * @return
     * 增加一个用户
     */
    @RequestMapping(value = "/addUser", method = RequestMethod.POST)
    @ResponseBody
    public AjaxJson addUser(HttpServletRequest request){
        AjaxJson j = new AjaxJson();
        Enumeration<?>  keys = request.getParameterNames();
        Map<String,Object> map = Maps.newHashMap();
        while(keys.hasMoreElements()){
        	String reqCode = keys.nextElement().toString();
        	map.put(reqCode,request.getParameter(reqCode));
        }
        try {
			userService.addUserOrUpdate(map);
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("系統忙，新增或更新用户【"+map.get("menuNum")+"】失败!");
			logger.error("新增或者更新用户【"+map.get("menuNum")+"】失败!",e);
		}
        if (logger.isDebugEnabled()) {
            logger.debug("请求【/metro/user/addUser】处理,响应对象【"+j+"】");
        }
        return j;
    }

    /**
     * @return
     * 删除一个用户
     */
    @RequestMapping(value = "/delUser", method = RequestMethod.GET)
    @ResponseBody
    public AjaxJson delUser(@RequestParam("loginNum") String loginNum) {
        AjaxJson j = new AjaxJson();
        try {
			userService.deleteUser(loginNum);
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("系統忙，删除用户【"+loginNum+"】失败!");
			logger.error("删除用户【"+loginNum+"】失败!",e);
		}
        if (logger.isDebugEnabled()) {
            logger.debug("请求【/metro/user/delUser】处理,响应对象【"+j+"】");
        }
        return j;
    }
}